package com.sunni.controller;

import com.sunni.entity.Book;
import com.sunni.entity.Reader;
import com.sunni.service.BookService;
import com.sunni.service.impl.BookServiceImpl;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/bookFindAll")
public class BookServlet extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method")==null ? "findAll" : req.getParameter("method");
        Integer page = req.getParameter("page")==null ? 1 : Integer.parseInt(req.getParameter("page")); // 判断前台传来的page是不是null, 是null page=1, 不是null page = page。
        Integer borrowPage = req.getParameter("borrowPage")==null ? 1 : Integer.parseInt(req.getParameter("borrowPage"));

        HttpSession session = null;
        Reader reader = null;
        Integer readerId = null;


        switch (method){
            case "findAll":
                List<Book> bookList = bookService.findAll(page);
                req.setAttribute("bookList",bookList);
                req.setAttribute("everyPageProject",6);
                req.setAttribute("nowPage",page);
                req.setAttribute("pageTotal",bookService.getPageTotal());
                req.getRequestDispatcher("index.jsp").forward(req,resp);
                break;
            case "addBorrow":
                Integer bookId = Integer.parseInt(req.getParameter("bookId"));
                session = req.getSession();
                reader = (Reader) session.getAttribute("reader");
                readerId = reader.getId();
                bookService.addBorrow(bookId,readerId);
                req.getRequestDispatcher("/bookFindAll?method=findAllBorrowByReaderid&readerId="+readerId).forward(req,resp);
                break;
            case "findAllBorrowByReaderid":
                session = req.getSession();
                reader = (Reader) session.getAttribute("reader");
                readerId = reader.getId();
                req.setAttribute("borrowList",bookService.findAllByReaderid(readerId,borrowPage));
                req.setAttribute("everyPageProject",6);
                req.setAttribute("nowPage",borrowPage);
                req.setAttribute("countBorrowPage",bookService.getPageCountBorrowByReaderid(readerId));
                req.getRequestDispatcher("borrow.jsp").forward(req,resp);
                break;
        }
    }
    @Test
    public void ControllerTest(){
        List<Book> bookList = bookService.findAll(222);
        for(Book book: bookList){
            System.out.println(book);
        }
    }
}
